#include <netinet/in.h>
#include <signal.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>

#include <linux/un.h>

#define SOCK_IPC_FILE "/home/hcgy/Documents/esm6800h/test/sock_ipc.txt"

int main(int argc, char **argv)
{
    int server_sockfd = -1;
    int client_sockfd = -1;
    socklen_t client_len = 0;
 
    struct sockaddr_un server_addr;
    struct sockaddr_un client_addr;
 
    // 创建流套接字
    server_sockfd = socket(AF_UNIX, SOCK_STREAM, 0);

    unlink(SOCK_IPC_FILE);
 
    // 设置服务器接收的连接地址和监听的端口
    server_addr.sun_family = AF_UNIX;                   // 指定网络套接字
    snprintf(server_addr.sun_path,sizeof(server_addr.sun_path),"%s",SOCK_IPC_FILE);
 
    // 绑定（命名）套接字
    bind(server_sockfd, (struct sockaddr *)&server_addr, sizeof(sockaddr_un));
 
    // 创建套接字队列，监听套接字
    listen(server_sockfd, 5);
 
    // 忽略子进程停止或退出信号
    signal(SIGCHLD, SIG_IGN);
 
    while (1)
    {
        char ch[128] = {'\0'};
        client_len = sizeof(client_addr);
        printf("Server waiting\n");
 
        // 接收连接，创建新的套接字
        client_sockfd = accept(server_sockfd, (struct sockaddr *)&client_addr, &client_len);
 
        if (fork() == 0)
        {
            // 子进程中，读取客户端发过来的信息，处理信息，再发送给客户端
            int readRet = read(client_sockfd, ch, 128);
            printf("server received data,%s",ch);
            sleep(5);
            write(client_sockfd, ch, readRet);
            close(client_sockfd);
            exit(0);
        }
        else
        {
            // 父进程中，关闭套接字
            close(client_sockfd);
        }
    }
}
